package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.dto.PageComDto;
import com.itheima.commen.ReturnSuccess;
import com.itheima.pojo.Companys;
import com.itheima.service.CompanysService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/companys")
public class CompanysController {
    @Autowired
    private CompanysService companysService;
    @Autowired
    private HttpServletRequest request;
    @GetMapping("/{id}")
    //id回显
    public Companys getCompanys(@PathVariable Integer id) {
        Companys byId = companysService.getById(id);
        return byId;

    }

    @PutMapping("/{id}")
    //修改
    public ReturnSuccess update(@RequestBody Companys companys) throws ParseException {
        boolean update = companysService.updateById(companys);
        if (update) {
            return ReturnSuccess.success();
        }
        return ReturnSuccess.error();
    }

    @PostMapping()
    //添加companys
    public ReturnSuccess add(@RequestBody Companys companys) {
        HttpSession session = request.getSession();
        Long userId = (Long) session.getAttribute("userId");
        String number = UUID.randomUUID().toString();
        companys.setNumber(number);
        String s = JSON.toJSONString(userId);
        Integer createdid = JSON.parseObject(s, Integer.class);
        companys.setCreatoriD(createdid);
        companys.setState(1);
        boolean save = companysService.save(companys);
        if (save) {
            return ReturnSuccess.success();
        }
        return ReturnSuccess.error();
    }

    @DeleteMapping("/{id}")
    //删除
    public ReturnSuccess delete(@PathVariable Integer id) {
        boolean remove = companysService.removeById(id);
        if (remove) {
            return ReturnSuccess.success();
        }
        return ReturnSuccess.error();
    }

    @PostMapping("/{id}/{state}")
    //状态修改
    public ReturnSuccess state(@PathVariable Integer id, @PathVariable Integer state) {
        ReturnSuccess returnSuccess = companysService.updateState(id, state);
        return returnSuccess;
    }

    @GetMapping()
    //查询
    public PageComDto search(Integer page, Integer pagesize,String tags,String province,String city,String shortName,Integer state) {
        PageComDto pageComDto=companysService.search(page,pagesize,tags,province,city,shortName,state);
        return pageComDto;
    }
}
